package com.zhentao.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.common.constants.WemediaConstants;
import com.zhentao.mapper.WmMaterialMapper;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.mapper.WmNewsMaterialMapper;
import com.zhentao.model.dtos.PageResponseResult;
import com.zhentao.model.dtos.ResponseResult;
import com.zhentao.model.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.WmNewsDto;
import com.zhentao.model.wemedia.dto.WmNewsPageReqDto;
import com.zhentao.model.wemedia.pojo.WmMaterial;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.model.wemedia.pojo.WmNewsMaterial;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.service.WmNewsService;
import com.zhentao.utils.common.WmUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;


    @Override
    public ResponseResult Newslist(WmNewsPageReqDto pageReqDto) {
        //检查参数是否为空
        if (pageReqDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前登录人的id
//        WmUser user = WmUserThreadLocalUtil.getUser();
//        if (user == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//        }

        //检查参数
        pageReqDto.checkParam();

        //分页
        IPage page = new Page(pageReqDto.getPage(), pageReqDto.getSize());

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //userId
        lambdaQueryWrapper.eq(WmUserThreadLocalUtil.getUser() == null, WmNews::getUserId, WmUserThreadLocalUtil.getUser().getId());
        //频道
        lambdaQueryWrapper.eq(pageReqDto.getChannelId() != null, WmNews::getChannelId, pageReqDto.getChannelId());
        //状态
        lambdaQueryWrapper.eq(pageReqDto.getStatus() != null, WmNews::getStatus, pageReqDto.getStatus());
        //关键字
        lambdaQueryWrapper.eq(pageReqDto.getKeyword() != null, WmNews::getLabels, pageReqDto.getKeyword());
        //开始时间和结束时间
        if (pageReqDto.getBeginPubDate() != null && pageReqDto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, pageReqDto.getBeginPubDate(), pageReqDto.getEndPubDate());
        }
        //按时间倒叙
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = wmNewsMapper.selectPage(page, lambdaQueryWrapper);

        PageResponseResult responseResult = new PageResponseResult((int) page.getPages(), (int) page.getSize(), (int) page.getTotal());

        responseResult.setCode(200);
        responseResult.setData(page.getRecords());
        responseResult.setErrorMessage("请求成功");


        return responseResult;
    }


    /**
     * 发布文章
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //把参数封装一下
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //补全代码
        wmNews.setUserId(WmUserThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);

        //提交时间
        if (dto.getStatus() == 1) {
            wmNews.setSubmitedTime(new Date());
        }

        //获取文章的封面
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //前端传递的是一个集合， 数据库里面需要使用字符串，用，隔开
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }

        // 处理 tinyint 不能是负数   -1 --》  4
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            dto.setType((short) 4);
            wmNews.setType((short) 4);
        }

        //5添加数据库
        //判断是新增操作还是修改操作
        if (dto.getId() == null) {
            wmNewsMapper.insert(wmNews);
        } else {
            //修改操作  需要删除素材与内容/以及封面的关系
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, dto.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            //修改
            wmNewsMapper.updateById(wmNews);
        }

        //新增关联
        //处理封面 封面是自己上传的   /   封面是自动上传的
        //图片是自己上传的
        if (dto.getType() != 4) {
            //把url转换成id
            List<String> images = dto.getImages();
            List<Integer> mids = new ArrayList<>();
            for (String image : images) {
                LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(WmMaterial::getUrl, image);
                WmMaterial wmMaterial = wmMaterialMapper.selectOne(lambdaQueryWrapper);
                mids.add(wmMaterial.getId());
                System.out.println("mids = " + mids);
            }
//            if (mids.size() > 0) {
            //把关系维护进去
            wmNewsMaterialMapper.saveRelations(mids, wmNews.getId(), (short) 1);
//            }


        } else {
            //自动获取封面
            //如何自动获取到封面  从内容里面获取
            List<String> images = new ArrayList<>();
            List<Map> maps = JSON.parseArray(dto.getContent(), Map.class);
            for (Map map : maps) {
                //传递过来是个图片
                if (map.get("type").equals("image")) {
                    //把获取到的图片保存到images里面 -list集合
                    images.add((String) map.get("value"));
                }
            }
            if (images.size() == 0) {
                //内容里面是没有图片的
                //没有图片的  页面是没有4的局部的  0  1  3；   没有图片，布局就是0
                WmNews wmNews1 = new WmNews();
                wmNews1.setId(wmNews.getId());
                wmNews1.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                wmNewsMapper.updateById(wmNews1);

            } else {
                //内容里面是有图片的   把图片设置成封面
                // size=1  type=1  size=2 type=1 size=3 type=3 size=4 type=3
                //有图片的
                if (images.size() == 1 || images.size() == 2) {
                    //修改type=1
                    WmNews wmNews1 = new WmNews();
                    wmNews1.setId(wmNews.getId());
                    wmNews1.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);

                    //1.news表里面得images字段
                    String newsImages = StringUtils.join(images, ",");
                    wmNews1.setImages(newsImages);
                    wmNewsMapper.updateById(wmNews1);

                    List<Integer> mids = new ArrayList<>();
                    for (String image : images) {
                        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(WmMaterial::getUrl, image);
                        WmMaterial wmMaterial = wmMaterialMapper.selectOne(lambdaQueryWrapper);
                        mids.add(wmMaterial.getId());
                    }
                    //把关系维护进去
                    wmNewsMaterialMapper.saveRelations(mids, wmNews.getId(), (short) 1);
                } else if (images.size() == 3) {
                    WmNews wmNews3 = new WmNews();
                    wmNews3.setId(wmNews.getId());
                    wmNews3.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);

                    String newsImages3 = StringUtils.join(images, ",");
                    wmNews3.setImages(newsImages3);
                    wmNewsMapper.updateById(wmNews3);
                    List<Integer> mids = new ArrayList<>();
                    for (String image : images) {
                        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(WmMaterial::getUrl, image);
                        WmMaterial wmMaterial = wmMaterialMapper.selectOne(lambdaQueryWrapper);
                        mids.add(wmMaterial.getId());
                    }
                    //把关系维护进去
                    wmNewsMaterialMapper.saveRelations(mids, wmNews.getId(), (short) 3);
                }
            }

        }

        //进行审核

        if (dto.getStatus() == 1) {
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }

//
//        //处理内容与素材直接的关系  从里面里面吧素材获取到url -- id  添加操作
//        if (dto.getId() == null) {
//            wmNewsMapper.insert(wmNews);
//
//        }


        //如果状态是0草稿  状态是1 【自动审核 ,人工审核】


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /***
     * 删除
     * */
    @Override
    public ResponseResult delNews(Integer id) {
//        LambdaQueryWrapper<WmNews> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper1.eq(WmNews::getId, id);
        wmNewsMapper.deleteById(id);
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, id);
        wmNewsMaterialMapper.delete(lambdaQueryWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /***
     * 修改
     * */
    @Override
    public ResponseResult updateOne(Integer id) {
//        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(WmNews::getId, id);
        WmNews wmNews = wmNewsMapper.selectById(id);
        return ResponseResult.okResult(wmNews);
    }


}

